package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理下单时间超时
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOut(){
        log.info("处理下单超时的任务～");
        // 获取到代付款和超过15分钟的订单
        List<Orders> orderList = orderMapper.getStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        if(orderList != null && orderList.size() > 0){
            for(Orders orders : orderList){
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时！自动取消！！");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }


    /**
     * 处理配送成功一天触发一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDelieveOrder(){
        log.info("处理配送成功一天触发一次");
        List<Orders> ordersList = orderMapper.getStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));

        if(ordersList != null && ordersList.size() > 0){
            for(Orders orders : ordersList){
                // 将配送中的订单超过一天的就改为已完成
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
